package com.kzd.gtboon.main

import android.Manifest
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.*
import com.kzd.gtboon.R
import com.kzd.gtboon.base.BaseViewModel
import com.kzd.gtboon.custom.setOnClickAntiShakeListener
import com.kzd.gtboon.databinding.FragmentMainServiceBinding
import com.kzd.gtboon.main.game.GameListFragment
import com.kzd.gtboon.main.popup.ServiceCodePopup
import com.kzd.gtboon.main.service.adapter.ServiceExchangeAdapter
import com.kzd.gtboon.utils.saveImageToGallery
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewBindingFragment
import com.module.lemlin.owner.ownerViewModel

class MainServiceFragment : OwnerViewBindingFragment<FragmentMainServiceBinding>() {

    companion object {
        private const val KEY_SERVICE_IS_HIDE_BACK = "KEY_SERVICE_IS_HIDE_BACK"
        fun newInstance(isHideBack: Boolean = false): MainServiceFragment {
            val bundle = Bundle().apply {
                putBoolean(KEY_SERVICE_IS_HIDE_BACK, isHideBack)
            }
            return MainServiceFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mServiceCodePopup: ServiceCodePopup by lazy {
        ServiceCodePopup(context = requireContext()) { _, type ->
            requestDangerousPermissions(arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ), requestCode = type)
        }
    }

    private val mServiceExchangeAdapter = ServiceExchangeAdapter()

    private val isHideBack: Boolean by lazy {
        arguments?.getBoolean(KEY_SERVICE_IS_HIDE_BACK) ?: false
    }

    private val mViewModel: BaseViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater, ViewGroup?, Boolean) -> FragmentMainServiceBinding
        get() = FragmentMainServiceBinding::inflate

    override fun initView() {
        BarUtils.addMarginTopEqualStatusBarHeight(mViewBinding.flMainServiceBar)

        if (isHideBack) {
            mViewBinding.flMainServiceBar.setLeftVisibility(View.VISIBLE)
        }

        mViewBinding.rvMainServiceBody.apply {
            layoutManager = LinearLayoutManager(context)
        }.adapter = mServiceExchangeAdapter

        mServiceExchangeAdapter.setOnItemChildClickListener { _, view, position ->
            val gameExchange = mServiceExchangeAdapter.getItem(position)
            if (view.id == R.id.tvServiceExchangeCopy) {
                ClipboardUtils.copyText(gameExchange.code)
                ToastUtils.showShort("兑换码:${gameExchange.code}\t已复制，去联系客服吧！")
            } else if (view.id == R.id.tvServiceExchangeConnect) {
                val image = mViewModel.userServiceLiveData.value
                    ?.data?.data?.qy_wx_img
                mServiceCodePopup.setContent(if (image.isNullOrEmpty()) {
                    R.mipmap.ic_40008
                } else image, 1)
                    .showPopupWindow()
            }
        }

        mViewBinding.llMainServiceQQ.setOnClickAntiShakeListener {
            toExternalAppQQ(requireActivity())
        }

        mViewBinding.llMainServiceWX.setOnClickAntiShakeListener {
            val image = mViewModel.userServiceLiveData.value
                ?.data?.data?.qy_wx_img
            mServiceCodePopup.setContent(if (image.isNullOrEmpty()) {
                R.mipmap.ic_40008
            } else image, 1)
                .showPopupWindow()
        }

        mViewBinding.ivMainServiceWX.setOnClickListener {
            val image = mViewModel.userServiceLiveData.value
                ?.data?.data?.gzh_img
            mServiceCodePopup.setContent(if (image.isNullOrEmpty()) {
                R.mipmap.ic_40007
            } else image, 2)
                .showPopupWindow()
        }

    }

    override fun initData() {
        mViewModel.userService()
        mViewModel.userExchangeCodeList()
    }

    override fun onRefreshLoad() {
        mViewModel.userExchangeCodeList()
    }

    override fun initViewMode() {
        mViewModel.userServiceLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
        })

        mViewModel.userExchangeCodeListLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            mServiceExchangeAdapter.setNewInstance(data)
        })
    }

    override fun handlePermissionResult(requestCode: Int, granted: Boolean): Boolean {
        if (!granted) {
            toast("请到应用设置中开启存储权限！")
            return false
        }
        val bitmap = BitmapFactory.decodeResource(resources,
            if (requestCode == 1) R.mipmap.ic_40008 else R.mipmap.ic_40007)
        val fileName = "${if (requestCode == 1) R.mipmap.ic_40008 else R.mipmap.ic_40007}.png"
        if (saveImageToGallery(requireContext(), bitmap, fileName)) {
            toast("已保存")
        } else {
            toast("保存失败")
        }
        return super.handlePermissionResult(requestCode, granted)
    }
}